#include "fileoperations.h"
using Org::FileOperations;

FileOperations::FileOperations()
{

}

// transforms a/b/c to a/d/c where orig_path = a/b/c  and new_dir = a/d
bf::path FileOperations::get_new_path(const bf::path &prev_path, const bf::path &orig_path, const bf::path &new_dir)
{
    int start = prev_path.string().size();
    int end = orig_path.string().size();

    string filename = orig_path.string().substr(start, end);

    bf::path new_path = new_dir.string() + filename;

    return new_path;
}

void FileOperations::tokenise(const string& str, vector<string>& tokens, const string& delimiters = "/")
{
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos)
    {
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        lastPos = str.find_first_not_of(delimiters, pos);
        pos = str.find_first_of(delimiters, lastPos);
    }
}


bool FileOperations::move_dir(const bf::path &prev_dir, const bf::path &dir, const bf::path &copy_to)
{
    if(bf::exists(dir) && bf::exists(copy_to))
    {
        bf::path cur_full = get_new_path(prev_dir, dir, copy_to);

        if(!bf::exists(cur_full))
            bf::rename(dir, cur_full);

        return true;
    }
    return false;
}

bool FileOperations::copy_dir(const bf::path &prev_dir, const bf::path &dir, const bf::path &copy_to)
{
    if(bf::exists(dir) && bf::exists(copy_to))
    {
        bf::path cur_full = get_new_path(prev_dir, dir, copy_to); //first level dir new/exit013 -> dnb/exit/exit013
        bf::create_directory(cur_full);

        bf::directory_iterator end_itr;

        for(bf::directory_iterator itr(dir.string()); itr!=end_itr; ++itr)
        {
            bf::path copy_to_path = get_new_path(dir, (*itr).path(), cur_full);

            if(is_directory((*itr).path())) // dir
                copy_dir(dir, (*itr).path(), cur_full);

            else // file
            {
                if(!bf::exists(copy_to_path))
                {
                    string f_path = (*itr).path().string();
                    string f_ext = f_path.substr(f_path.size()-3, f_path.size());
                    bf::copy_file((*itr).path(), copy_to_path);
                }
            }
        }
        return true;
    }
    return false;
}

bool FileOperations::del_dir(const bf::path &dir )
{
    bf::remove_all(dir);
    if(!bf::exists(dir)) return true;
    return false;
}

bool FileOperations::del_file(const bf::path &file )
{
    bf::remove(file);
    if(!bf::exists(file)) return true;
    return false;
}

bool FileOperations::rename(const bf::path &from_path, const bf::path &to_path)
{
    if(bf::exists(to_path)) return false;
    bf::rename(from_path, to_path);
    if(bf::exists(to_path)) return true;
    return false;
}
